<template>
  <div class="chat-container">
    <el-card class="chat-list">
      <div slot="header" class="chat-header">
        <span class="title">好友列表</span>
      </div>
      <div class="search-box">
        <el-input
            v-model="searchKeyword"
            placeholder="搜索好友"
            prefix-icon="el-icon-search"
            clearable
        />
      </div>
      <div class="friend-list">
        <div
            v-for="item in filteredFriends"
            :key="item.id"
            class="friend-item"
            :class="{ active: currentFriend?.id === item.id }"
            @click="onSelectFriend(item)"
        >
          <el-avatar :size="40" :src="item.avatar">
            {{ item.nickname.charAt(0) }}
          </el-avatar>
          <div class="friend-info">
            <div class="friend-header">
              <span class="name">{{ item.nickname }}</span>
              <span class="role-tag">{{ item.role === 1 ? '老师' : '学生' }}</span>
            </div>
<!--            <div class="friend-status">-->
<!--              <span class="status" :class="item.online ? 'online' : 'offline'">-->
<!--                {{ item.online ? '在线' : '离线' }}-->
<!--              </span>-->
<!--              <el-badge-->
<!--                  v-if="item.unread_count"-->
<!--                  :value="item.unread_count"-->
<!--                  class="unread-badge"-->
<!--              />-->
<!--            </div>-->
          </div>
        </div>
      </div>
    </el-card>

    <el-card class="chat-content" v-if="currentFriend">
      <div slot="header" class="chat-header">
        <span class="title">{{ currentFriend.name }}</span>
        <div class="header-actions">
          <span class="status-text" :class="currentFriend.online ? 'online' : 'offline'">
            {{ currentFriend.online ? '在线' : '离线' }}
          </span>
          <el-dropdown trigger="click" @command="handleCommand">
            <span class="el-dropdown-link">
              <i class="el-icon-more"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="clear">清空聊天记录</el-dropdown-item>
              <el-dropdown-item command="block">屏蔽消息</el-dropdown-item>
              <el-dropdown-item command="delete" divided>删除好友</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <div class="message-list" ref="messageList">
        <div
            v-for="(message, index) in messages"
            :key="index"
            class="message-item"
            :class="{ 'message-mine': message.is_mine }"
        >
          <el-avatar
              :size="36"
              :src="message.is_mine ? userInfo.avatar : currentFriend.avatar"
          >
            {{ message.is_mine ? userInfo.nickname.charAt(0) : currentFriend.nickname.charAt(0) }}
          </el-avatar>
          <div class="message-content">
            <div class="message-info">
              <span class="name">{{ message.is_mine ? userInfo.nickname : currentFriend.nickname }}</span>
              <span class="time">{{ formatTime(message.createTime) }}</span>
            </div>
            <div class="message-bubble">{{ message.content }}</div>
          </div>
        </div>
      </div>
      <div class="message-input">
        <el-input
            type="textarea"
            v-model="inputMessage"
            :rows="3"
            placeholder="请输入消息"
            @keyup.enter.native="onSendMessage"
        />
        <div class="input-actions">
          <el-button type="primary" @click="onSendMessage">发送</el-button>
        </div>
      </div>
    </el-card>

    <el-dialog
        title="添加好友"
        :visible.sync="showNewChat"
        width="500px"
    >
      <div class="new-chat-content">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="搜索老师" name="teacher">
            <el-input
                v-model="teacherSearch"
                placeholder="输入老师姓名搜索"
                prefix-icon="el-icon-search"
                clearable
                style="margin-bottom: 15px"
            />
            <div class="user-list">
              <div
                  v-for="teacher in filteredTeachers"
                  :key="teacher.id"
                  class="user-item"
                  @click="onAddFriend(teacher)"
              >
                <el-avatar :size="40" :src="teacher.avatar">
                  {{ teacher.name.charAt(0) }}
                </el-avatar>
                <div class="user-info">
                  <div class="name">{{ teacher.name }}</div>
                  <div class="role">{{ teacher.role }}</div>
                </div>
                <el-button
                  size="mini"
                  type="primary"
                  :disabled="teacher.is_friend"
                >
                  {{ teacher.is_friend ? '已添加' : '添加' }}
                </el-button>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="搜索学生" name="student">
            <el-input
                v-model="studentSearch"
                placeholder="输入学生姓名搜索"
                prefix-icon="el-icon-search"
                clearable
                style="margin-bottom: 15px"
            />
            <div class="user-list">
              <div
                  v-for="student in filteredStudents"
                  :key="student.id"
                  class="user-item"
                  @click="onAddFriend(student)"
              >
                <el-avatar :size="40" :src="student.avatar">
                  {{ student.name.charAt(0) }}
                </el-avatar>
                <div class="user-info">
                  <div class="name">{{ student.name }}</div>
                  <div class="role">{{ student.role }}</div>
                </div>
                <el-button
                  size="mini"
                  type="primary"
                  :disabled="student.is_friend"
                >
                  {{ student.is_friend ? '已添加' : '添加' }}
                </el-button>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { http } from "@/api";
import dayjs from 'dayjs';

export default {
  name: "ChatIndex",
  data() {
    return {
      searchKeyword: '',
      teacherSearch: '',
      studentSearch: '',
      showNewChat: false,
      activeTab: 'teacher',
      currentFriend: null,
      inputMessage: '',
      messages: [],
      friends: [],
      teachers: [],
      students: [],
      userInfo: this.$store.state.user.userInfo,
      loading: false,
      pollingTimer: null
    }
  },
  computed: {
    filteredFriends() {
      if (!this.searchKeyword) {
        return this.friends.map(item => {
          return {
            ...item,
          }
        })
      }
      const keyword = this.searchKeyword.toLowerCase()
      return this.friends.filter(friend =>
        friend.nickname.toLowerCase().includes(keyword)
      ).map(item => {
        return {
          ...item,
        }
      })
    },
    filteredTeachers() {
      if (!this.teacherSearch) {
        return this.teachers
      }
      const keyword = this.teacherSearch.toLowerCase()
      return this.teachers.filter(teacher =>
        teacher.name.toLowerCase().includes(keyword)
      )
    },
    filteredStudents() {
      if (!this.studentSearch) {
        return this.students
      }
      const keyword = this.studentSearch.toLowerCase()
      return this.students.filter(student =>
        student.name.toLowerCase().includes(keyword)
      )
    }
  },
  created() {
    this.getFriendList()
  },
  beforeDestroy() {
    if (this.pollingTimer) {
      clearInterval(this.pollingTimer)
    }
  },
  methods: {
    formatTime(time) {
      return dayjs(time).format('MM-DD HH:mm')
    },
    async getFriendList() {
      try {
        const res = await http.message.getChatFriends(this.$store.state.user.userInfo.id)
        this.friends = res.data
      } catch (error) {
        console.error(error)
        this.$message.error('获取好友列表失败')
      }
    },
    async getMessageList(friendId) {
      try {
        const res = await http.message.getUnread(this.$store.state.user.userInfo.id, friendId)
        if (res.data && res.data.length > 0) {
          this.messages = res.data.map(item => {
            return {
              ...item,
              is_mine: item.senderId === this.$store.state.user.userInfo.id,
              userInfo: this.$store.state.user.userInfo
            }
          })
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        }
      } catch (error) {
        console.error(error)
        this.$message.error('获取消息记录失败')
      }
    },
    onSelectFriend(friend) {
      this.currentFriend = friend
      this.getMessageList(friend.id)

      if (this.pollingTimer) {
        clearInterval(this.pollingTimer)
      }

      this.pollingTimer = setInterval(async () => {
        try {
          this.getMessageList(friend.id)
        } catch (error) {
          console.error('轮询未读消息失败:', error)
        }
      }, 5000)
    },
    async onSendMessage() {
      if (!this.inputMessage.trim()) {
        return
      }
      try {
        await http.message.send({
          content: this.inputMessage,
          senderId: this.$store.state.user.userInfo.id,
          receiverId: this.currentFriend.id,
          isRead: false
        })
        this.messages.push({
          is_mine: true,
          content: this.inputMessage,
          time: new Date(),
          status: 'sent'
        })
        this.inputMessage = ''
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      } catch (error) {
        console.error(error)
        this.$message.error('发送消息失败')
      }
    },
    scrollToBottom() {
      const messageList = this.$refs.messageList
      if (messageList) {
        messageList.scrollTop = messageList.scrollHeight
      }
    },
    handleCommand(command) {
      switch (command) {
        case 'clear':
          this.clearMessages()
          break
        case 'block':
          this.blockFriend()
          break
        case 'delete':
          this.deleteFriend()
          break
      }
    },
    async clearMessages() {
      try {
        await this.$confirm('确认清空与该好友的聊天记录吗？', '提示', {
          type: 'warning'
        })
        await http.message.clearMessages(this.currentFriend.id)
        this.messages = []
        this.$message.success('清空成功')
      } catch (error) {
        if (error !== 'cancel') {
          console.error(error)
          this.$message.error('清空失败')
        }
      }
    },
    async blockFriend() {
      try {
        await this.$confirm('确认屏蔽该好友的消息吗？', '提示', {
          type: 'warning'
        })
        await http.message.blockFriend(this.currentFriend.id)
        this.$message.success('屏蔽成功')
        this.getFriendList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error(error)
          this.$message.error('屏蔽失败')
        }
      }
    },
    async deleteFriend() {
      try {
        await this.$confirm('确认删除该好友吗？删除后将无法接收对方的消息。', '提示', {
          type: 'warning'
        })
        await http.message.deleteFriend(this.currentFriend.id)
        this.$message.success('删除成功')
        this.currentFriend = null
        this.getFriendList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error(error)
          this.$message.error('删除失败')
        }
      }
    },
    async onAddFriend(user) {
      if (user.is_friend) {
        return
      }
      try {
        await http.message.addFriend(user.id)
        this.$message.success('添加成功')
        this.getFriendList()
        this.showNewChat = false
      } catch (error) {
        console.error(error)
        this.$message.error('添加失败')
      }
    },
    onNewChat() {
      this.showNewChat = true
    }
  }
}
</script>

<style lang="scss" scoped>
.chat-container {
  height: calc(100vh - 120px);
  display: flex;
  gap: 20px;
  padding: 20px;
  background: #f5f7fa;

  .chat-list {
    width: 300px;
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .chat-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 0;

      .title {
        font-size: 16px;
        font-weight: bold;
      }
    }

    .search-box {
      padding: 10px 0;
    }

    .friend-list {
      flex: 1;
      overflow-y: auto;

      .friend-item {
        display: flex;
        align-items: center;
        padding: 10px;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          background: #f5f7fa;
        }

        &.active {
          background: #ecf5ff;
        }

        .friend-info {
          flex: 1;
          margin-left: 10px;
          overflow: hidden;

          .friend-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 5px;

            .name {
              font-weight: 500;
              color: #303133;
            }

            .role-tag {
              font-size: 12px;
              color: #909399;
            }
          }

          .friend-status {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .status {
              font-size: 12px;

              &.online {
                color: #67C23A;
              }

              &.offline {
                color: #909399;
              }
            }
          }
        }
      }
    }
  }

  .chat-content {
    flex: 1;
    height: 100%;
    display: flex;
    flex-direction: column;

    .chat-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 0;

      .title {
        font-size: 16px;
        font-weight: bold;
      }

      .header-actions {
        display: flex;
        align-items: center;
        gap: 10px;

        .status-text {
          font-size: 12px;

          &.online {
            color: #67C23A;
          }

          &.offline {
            color: #909399;
          }
        }
      }
    }

    .message-list {
      flex: 1;
      overflow-y: auto;
      padding: 20px;

      .message-item {
        display: flex;
        margin-bottom: 20px;

        &.message-mine {
          flex-direction: row-reverse;

          .message-content {
            margin-left: 0;
            margin-right: 10px;

            .message-info {
              text-align: right;
            }

            .message-bubble {
              background: #409EFF;
              color: #fff;
              border-radius: 10px 2px 10px 10px;
            }
          }
        }

        .message-content {
          margin-left: 10px;
          max-width: 70%;

          .message-info {
            margin-bottom: 5px;

            .name {
              font-size: 14px;
              color: #606266;
              margin-right: 10px;
            }

            .time {
              font-size: 12px;
              color: #909399;
            }
          }

          .message-bubble {
            padding: 10px 15px;
            background: #f5f7fa;
            border-radius: 2px 10px 10px 10px;
            word-break: break-all;
          }
        }
      }
    }

    .message-input {
      padding: 20px;
      border-top: 1px solid #ebeef5;

      .input-actions {
        margin-top: 10px;
        text-align: right;
      }
    }
  }
}

.new-chat-content {
  .user-list {
    max-height: 400px;
    overflow-y: auto;

    .user-item {
      display: flex;
      align-items: center;
      padding: 10px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        background: #f5f7fa;
      }

      .user-info {
        flex: 1;
        margin-left: 10px;

        .name {
          font-weight: 500;
          color: #303133;
          margin-bottom: 5px;
        }

        .role {
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }
}
</style>
